package com.efounder.image.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.Log;

public class ImageUtils {

	/**
	 * 压缩原来图片 防止内存溢出崩溃
	 * @param filePath
	 * @return
	 */
	public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }
	
	public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int inSampleSize = 1;

	    if (height > reqHeight || width > reqWidth) {
	             final int heightRatio = Math.round((float) height/ (float) reqHeight);
	             final int widthRatio = Math.round((float) width / (float) reqWidth);
	             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
	    }
	        return inSampleSize;
	}
	/**
	 * 保存图片至系统相册
	 */
//	public static void saveImageToGallery(Context context, Bitmap bmp) {
//	    // 首先保存图片
//	    File appDir = new File(Environment.getExternalStorageDirectory(), "HIK");
//	    if (!appDir.exists()) {
//	        appDir.mkdir();
//	    }
//	    String fileName = System.currentTimeMillis() + ".jpg";
//	    File file = new File(appDir, fileName);
//	    try {
//	        FileOutputStream fos = new FileOutputStream(file);
//	        bmp.compress(CompressFormat.JPEG, 100, fos);
//	        fos.flush();
//	        fos.close();
//	    } catch (FileNotFoundException e) {
//	        e.printStackTrace();
//	    } catch (IOException e) {
//	        e.printStackTrace();
//		}
//	    
//	    // 其次把文件插入到系统图库
//	    try {
//	        MediaStore.Images.Media.insertImage(context.getContentResolver(),
//					file.getAbsolutePath(), fileName, null);
//	    } catch (FileNotFoundException e) {
//	        e.printStackTrace();
//	    }
//	    // 最后通知图库更新
//	    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
//	}
	/**
	 * 写图片文件到SD卡
	 * 
	 * @throws IOException
	 */
	public static void saveImageToSD(Context ctx, String filePath,
			Bitmap bitmap, int quality) throws IOException {
		if (bitmap != null) {
			File file = new File(filePath.substring(0,filePath.lastIndexOf(File.separator)));
			
			if (!file.exists()) {
				file.mkdirs();
			}
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
			bitmap.compress(CompressFormat.JPEG, quality, bos);
			bos.flush();
			bos.close();
			if (ctx != null) {
//				scanPhoto(ctx, filePath);
				updateGallery(ctx, filePath);
			}
		}
	}
	/**
	 * 让Gallery上能马上看到该图片   android4.4之后  报错 暂时放弃该方法
	 */
	public static void scanPhoto(Context ctx, String imgFileName) {
		Intent mediaScanIntent = new Intent(
				Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File file = new File(imgFileName);
		Uri contentUri = Uri.fromFile(file);
		mediaScanIntent.setData(contentUri);
		ctx.sendBroadcast(mediaScanIntent);
	}
	
	/**
	 * 刷新gallery  
	 * @param context
	 * @param filename
	 */
	public static void updateGallery(Context context,String filename)//filename是我们的文件全名，包括后缀哦
	{
		MediaScannerConnection.scanFile(context,
		          new String[] { filename }, null,
		          new MediaScannerConnection.OnScanCompletedListener() {
		      public void onScanCompleted(String path, Uri uri) {
		          Log.i("ExternalStorage", "Scanned " + path + ":");
		          Log.i("ExternalStorage", "-> uri=" + uri);
		      }
		 });
	}
	
//	public static Uri exportToGallery(Context context,String filename) {
//        // Save the name and description of a video in a ContentValues map.
//        final ContentValues values = new ContentValues(2);
//        values.put(MediaStore.Video.Media.MIME_TYPE, "image/jpeg");
//        values.put(MediaStore.Video.Media.DATA, filename);
//        // Add a new record (identified by uri)
//        final Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                values);
//        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
//                Uri.parse("file://"+ filename)));
//        return uri;
//    }
}